package com.destroyer.core.util;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.destroyer.common.util.Func;
import com.destroyer.core.entity.base.BaseBO;
import com.destroyer.core.entity.base.BaseEntity;

import java.util.List;

/**
 * 标题：QueryWrapperUtils
 * 说明：MP SQL包装工具类
 * 时间：2023/8/5
 * 作者：admin
 */
public class MpSqlWrapperUtils {


    /**
     * 构造MP 查询Wrapper
     * @param req
     * @param <T>
     * @param <Q>
     * @return
     */
    public static <T extends BaseEntity, Q extends BaseBO> LambdaQueryWrapper<T> buildQueryWrapper(Q req) {
        QueryWrapper<T> queryWrapper = Wrappers.query();
        //动态多字段排序
        if(Func.isNotEmpty(req.getAscs())){
            for(String asc:req.getAscs()){
                asc = StrUtil.toUnderlineCase(asc).toLowerCase();
                queryWrapper.orderByAsc(asc);
            }
        }
        if(Func.isNotEmpty(req.getDescs())){
            for(String desc:req.getDescs()){
                desc = StrUtil.toUnderlineCase(desc).toLowerCase();
                queryWrapper.orderByAsc(desc);

            }
        }
        LambdaQueryWrapper<T> rsp = queryWrapper.lambda();
        //通用字段
        rsp.eq(null != req.getId(), T::getId, req.getId());
        //构建列表查询条件
        buildListConditionWrapper(rsp,T::getId,req.getIdList());
        rsp.eq(null != req.getCreateTime(), T::getCreateTime, req.getCreateTime());
        rsp.ge(null != req.getCreateTimeStart(), T::getCreateTime, req.getCreateTimeStart());
        rsp.le(null != req.getCreateTimeEnd(), T::getCreateTime, req.getCreateTimeEnd());
        rsp.eq(null != req.getUpdateTime(), T::getUpdateTime, req.getUpdateTime());
        rsp.ge(null != req.getUpdateTimeStart(), T::getUpdateTime, req.getUpdateTimeStart());
        rsp.le(null != req.getUpdateTimeEnd(), T::getUpdateTime, req.getUpdateTimeEnd());
        rsp.eq(null != req.getCreateUser(), T::getCreateUser, req.getCreateUser());
        rsp.eq(null != req.getUpdateUser(), T::getUpdateUser, req.getUpdateUser());
        return rsp;
    }


    /**
     * 构建列表查询条件包装器
     * @param wrapper
     * @param sFunction
     * @param list
     * @param <T>
     */
    public static  <T extends BaseEntity> void buildListConditionWrapper(LambdaQueryWrapper<T> wrapper,SFunction<T,?> sFunction, List list){
        wrapper.in(Func.isNotEmpty(list),sFunction,list);
        wrapper.apply(null != list && list.size() == 0,"FALSE");
    }







}
